﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MechAddin.Common
{
    public static class ThisString
    {
        public static double Parse(this string str)
        {
            if (string.IsNullOrEmpty(str)) return 0d;

            int index = 0;
            double result = 0d;
            int sign = 1;
            double fraction = 0d;
            int fractionDigits = 0;
            int exponent = 0;
            int exponentSign = 1;

            // 1. 处理符号
            if (str[index] == '-' || str[index] == '+')
            {
                sign = str[index] == '-' ? -1 : 1;
                index++;
            }

            // 2. 处理整数部分
            while (index < str.Length && str[index] >= '0' && str[index] <= '9')
            {
                result = result * 10 + (str[index] - '0');
                index++;
            }

            // 3. 处理小数部分
            if (index < str.Length && str[index] == '.')
            {
                index++;
                double scale = 1d;
                while (index < str.Length && str[index] >= '0' && str[index] <= '9')
                {
                    fraction = fraction * 10 + (str[index] - '0');
                    scale *= 10;
                    index++;
                    fractionDigits++;
                }
                if (fractionDigits > 0)
                {
                    result += fraction / scale;
                }
            }

            // 4. 处理科学计数法（e/E）
            if (index < str.Length && (str[index] == 'e' || str[index] == 'E'))
            {
                index++;
                // 处理指数符号
                if (index < str.Length && (str[index] == '-' || str[index] == '+'))
                {
                    exponentSign = str[index] == '-' ? -1 : 1;
                    index++;
                }
                // 处理指数值
                while (index < str.Length && str[index] >= '0' && str[index] <= '9')
                {
                    exponent = exponent * 10 + (str[index] - '0');
                    index++;
                }
            }
            // 5. 应用科学计数法
            if (exponent != 0)
            {
                exponent *= exponentSign;
                double power = 1d;
                for (int i = 0; i < exponent; i++) power *= 10;
                for (int i = 0; i > exponent; i--) power /= 10;
                result *= power;
            }
            return result * sign;
        }
    }
}
